%include "conf.inc"
%include "pm.inc"
%include "desc.inc"
	
	;; 简单的中断例子
	org	OffsetOfLoader - 2
loader_len:	dw	end - start
	jmp	start

	[SECTION .s16]
	[BITS 16]
start:
	mov	si, LoaderMessage
	call	__puts

	InitDescriptor SEG_CODE32, DESC_CODE32
	InitDescriptor SEG_DATA,   DESC_DATA
	InitDescriptor SEG_STACK0, DESC_STACK0

	LoadGdt	DESC_GDT, GdtPtr
	EnterPMModel

	jmp	dword	Code32Sel:0
__puts:
	pusha
	mov	ah, 0x0e
	xor	bh, bh
	.loop:
	lodsb
	test	al, al
	jz	.done
	int	0x10
	jmp	.loop
	.done:
	popa
	ret

LoaderMessage:	db	'this is loader....', 13, 10, 0
end:

	[SECTION .s32]
	[BITS	32]
SEG_CODE32:
	mov	ax, VideoSel
	mov	gs, ax
	mov	ax, DataSel
	mov	ds, ax
	mov	ax, Stack0Sel
	mov	ss, ax
	mov	esp, TopOfStack0

	
	mov	ah, 0Ch
	mov	edi, (80 * 21 + 0) * 2
	mov	esi, MessageOffset
.1:
	lodsb
	cmp	al, 0
	jz	.2
	mov	[gs:edi], ax
	add	edi, 2
	jmp	.1
.2:

	jmp	$

code32_tail:	db	'tail of code32 seg'
	
	SegCode32Len	equ	$ - SEG_CODE32
	
	[SECTION .gdt]
	[BITS	32]
SEG_GDT:
DESC_GDT:	Descriptor	0,	0,			0
DESC_CODE32:	Descriptor	0, 	SegCode32Len - 1, 	DA_C + DA_32
DESC_STACK0:	Descriptor	0,	TopOfStack0,		DA_DRWA	+ DA_32
DESC_DATA:	Descriptor	0,	SegDataLen - 1,		DA_DRW
DESC_VIDEO:	Descriptor	0B8000h,0ffffh, 		DA_DRW
	GdtLen	equ	$ - SEG_GDT
	GdtPtr	dw	GdtLen	- 1
		dd	0

	Code32Sel	equ	DESC_CODE32	-	DESC_GDT
	Stack0Sel	equ	DESC_STACK0	-	DESC_GDT
	DataSel		equ	DESC_DATA	-	DESC_GDT
	VideoSel	equ	DESC_VIDEO	-	DESC_GDT

	[SECTION .data]
	[BITS	32]
SEG_DATA:
MessageOffset	equ	$ - $$
ProtectedMessage:	db	"In Protected Model....", 0
	SegDataLen	equ	$ - SEG_DATA

	[SECTION .stack0]
	[BITS	32]
SEG_STACK0:
	times		64	db	0
	TopOfStack0	equ	$ - SEG_STACK0 - 1 ; 下标从 0 开始
	SegStack0Len	equ	$ - SEG_STACK0